package Vista;

import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;

import Vista.LogIn;
import Vista.NewAccount;

import InfoCliente.*;
import GestionDeDatos.GestorBD;

public class View {
	   
	   private static final String LogIn = "LogIn";
	   private static final String NewAccount = "NewAccount";
	   private static final String MainPage = "MainPage";
	   
	   private static final String Inicio = "Inicio";
	   private static final String Notif = "Notificacion";
	   private static final String Cargar = "CargarH";
	   private static final String Agregar = "AgregarA";
	   private static final String Consultar = "Consultar";
	   
	   private CardLayout cardlayout = new CardLayout();
	   private JPanel mainPanel  = new JPanel(cardlayout);
	   private LogIn logInPanel = new LogIn();
	   private NewAccount newAccountPanel = new NewAccount();
	   private MainPage mainPagePanel = new MainPage();
	   
	   public static int id;
	   public static String pass;

	   public View() {
		   
	      mainPanel.add(logInPanel.getMainComponent(), LogIn);
	      mainPanel.add(newAccountPanel.getMainComponent(), NewAccount);
	      mainPanel.add(mainPagePanel.getMainComponent(), MainPage);

	      logInPanel.NewAccountActionListener(new ActionListener() {
	         @Override
	         public void actionPerformed(ActionEvent e) {
	        	logInPanel.clearTextFields();
	        	newAccountPanel.clearTextFields();
	            cardlayout.show(mainPanel, NewAccount);
	            }
	      });
	      
	      logInPanel.LogInActionListener(new ActionListener() {
		         @Override
		         public void actionPerformed(ActionEvent e) {
		        	 

		        	 if ((logInPanel.getStringPadron().isEmpty() == true) ||
		        		(logInPanel.getPass().isEmpty() == true)) {
		        		 JOptionPane.showMessageDialog(mainPanel, "Hay campos sin completar.", "Mensaje", JOptionPane.PLAIN_MESSAGE);
		        		 return;
		        	 }
		        	 
		        	 UsuarioActivo usuarioActivo;
		        		 
		        	try {
		        		usuarioActivo = new UsuarioActivo(logInPanel.getPadron(), logInPanel.getPass());
		        		GestorBD.Gestor().IniciarSesion(usuarioActivo);
		        	} catch (NumberFormatException exception) {
	     				JOptionPane.showMessageDialog(mainPanel, "Padron Invalido.  Solo caracteres numericos.", "Mensaje", JOptionPane.PLAIN_MESSAGE);	
	     				return;
		        	} catch (Exception exception) {
		        		JOptionPane.showMessageDialog(mainPanel, exception.getMessage());
		        		return;
		        	}
		        	
		        	try {
		        		id = logInPanel.getPadron();
		        	} catch (Exception exception) {
		        		JOptionPane.showMessageDialog(mainPanel, exception.getMessage());
		        		return;
		        	}
		        	
	        		pass = logInPanel.getPass();
		        		
		    		int cantidad = 0;
		    		String[][] items = {};
		    				
		    		try {
		    			items = GestorBD.Gestor().ObtenerSolicitudes(usuarioActivo).getRegisters(); 	
		    		} catch (Exception exception) {
		    			JOptionPane.showMessageDialog(mainPanel, exception.getMessage());
		    		}
		    		
		    		cantidad = items.length;
	    			mainPagePanel.getJButtonNotificaciones().setText("Notificaciones (" + cantidad + ")");
	    			mainPagePanel.getNotif().setCantidad(mainPagePanel);
		        		
		        	logInPanel.clearTextFields();
		        	newAccountPanel.clearTextFields();
		            cardlayout.show(mainPanel, MainPage);
		            
		        	 String[][] data = {};
		        	 String[] col = {};
		        	 
		        	 if (mainPagePanel.getInicio().getAmigosIsSelected() == true) {
		        		 try {
		        			 data = GestorBD.Gestor().ObtenerAmistades(usuarioActivo).getRegisters(); 
		        			 col = GestorBD.Gestor().ObtenerAmistades(usuarioActivo).getFields();
		        		 } catch (Exception exception) {

		        		 }
		        	 
		        	 } else {			        	 
			        	try {
			        		String[] col1 = {"codigoMateria", "materia", "curso", "catedra", "tipo", "dia", "inicio", "fin", "sede", "aula"};
			        		col = col1;
			        		data = GestorBD.Gestor().ObtenerInscripciones(usuarioActivo).getRegisters(col1);
			        	} catch (Exception exception) {

			        	}
			        	 
		        	 }
	        		
		        	DefaultTableModel dm = new DefaultTableModel(data, col);
			        mainPagePanel.getTable().setModel(dm);  
		        	 
		         }

		      });
	      
	      newAccountPanel.BackActionListener(new ActionListener() {
		         @Override
		         public void actionPerformed(ActionEvent e) {
			        newAccountPanel.clearTextFields();
		            cardlayout.show(mainPanel, LogIn);
		         }
		      });
	      
	      newAccountPanel.SaveActionListener(new ActionListener() {
		         @Override
		         public void actionPerformed(ActionEvent e) {  
		        	
		        	 if ((newAccountPanel.getNombre().isEmpty() == true) ||
				        (newAccountPanel.getApellido().isEmpty() == true) ||
				        (newAccountPanel.getStringPadron().isEmpty() == true) ||
				        (newAccountPanel.getMail().isEmpty() == true) ||
				        (newAccountPanel.getPass().isEmpty() == true) ||
				        (newAccountPanel.getPass2().isEmpty() == true)) {
				        	JOptionPane.showMessageDialog(mainPanel, "Hay campos sin completar.", "Mensaje", JOptionPane.PLAIN_MESSAGE);
				        	return;
				        }
				        	 
				      if (newAccountPanel.getPass().equals( newAccountPanel.getPass2()) == false) {
				        	JOptionPane.showMessageDialog(mainPanel, "Las contraseñas son diferentes. Vuelva a ingresar.", "Notificacion", JOptionPane.PLAIN_MESSAGE);
				        	return;
				      }
				        	 			        
					  
				      try {
				    	  Usuario usuario = new Usuario(newAccountPanel.getPadron(), newAccountPanel.getNombre(), newAccountPanel.getApellido(), newAccountPanel.getMail(), newAccountPanel.getPass());
				          GestorBD.Gestor().CrearNuevoUsuario(usuario);
						  cardlayout.show(mainPanel, LogIn);
				          JOptionPane.showMessageDialog(mainPanel, "Su cuenta ha sido creada satisfactoriamente", "Notificacion", JOptionPane.PLAIN_MESSAGE);
				          } catch (NumberFormatException exception) {
				        	 JOptionPane.showMessageDialog(mainPanel, "Padron Invalido.  Solo caracteres numericos.", "Mensaje", JOptionPane.PLAIN_MESSAGE);	
			     			 return; 
				      
		         		  } catch (Exception exception) {
				            JOptionPane.showMessageDialog(mainPanel, exception.getMessage());
				            return;
				          }
					    	
				     }
			});
	      
	      mainPagePanel.InicioActionListener(new ActionListener() {
		         @Override
		         public void actionPerformed(ActionEvent e) {  
		        	 
	        		 UsuarioActivo usuarioActivo = new UsuarioActivo(View.id, View.pass);
	        		 String[][] data = {};
	        		 String[] col = {};
	        		 
		        	 if (mainPagePanel.getInicio().getAmigosIsSelected() == true) {
		        		 
		        		 try {
		        			 data = GestorBD.Gestor().ObtenerAmistades(usuarioActivo).getRegisters(); 
		        			 col = GestorBD.Gestor().ObtenerAmistades(usuarioActivo).getFields();
		        		 } catch (Exception exception) {

		        		 }
		        	 
		        	 } else {

			        	 
			        	try {
			        		String[] col1 = {"codigoMateria", "materia", "curso", "catedra", "tipo", "dia", "inicio", "fin", "sede", "aula"};
			        		col = col1;
			        		data = GestorBD.Gestor().ObtenerInscripciones(usuarioActivo).getRegisters(col1); 
			        	} catch (Exception exception) {

			        	}
			        	 
		        	 }

		        	DefaultTableModel dm = new DefaultTableModel(data, col);
			        mainPagePanel.getTable().setModel(dm);
		        	mainPagePanel.switchPanel(Inicio);	  

		        			        	 
		         }
		      }); 
	      
	      mainPagePanel.NotifActionListener(new ActionListener() {
		         @Override
		         public void actionPerformed(ActionEvent e) {  
		        	 mainPagePanel.switchPanel(Notif);	
		        	 
		        	 UsuarioActivo usuarioActivo = new UsuarioActivo(View.id, View.pass);
					 String[] fields = {"nombre", "apellido"};
					 String[][] items = {};
					 
						try {		
							items = GestorBD.Gestor().ObtenerSolicitudes(usuarioActivo).getRegisters(fields); 
						} catch(NullPointerException ex) {
							JOptionPane.showMessageDialog(mainPanel, "Problemas de conexion de usuario.  Vuelva a ingresar.");
							cardlayout.show(mainPanel, LogIn);
							return;
		         		} catch (Exception exception) {
							JOptionPane.showMessageDialog(mainPanel, exception.getMessage());
						}
						
						if (items.length > 0) {
							mainPagePanel.getNotif().getDefaultComboBox().removeAllElements();
							for (int i=0; i < items.length; i++ ) {
								mainPagePanel.getNotif().getDefaultComboBox().addElement(items[i][0] + " " + items[i][1]);
							}
						} else {
							mainPagePanel.getNotif().getDefaultComboBox().removeAllElements();
							mainPagePanel.getNotif().getDefaultComboBox().addElement("(vacio)");
						}
						
		    			int cantidad = 0;
		    			items = null;
		    			
		    			try {
		    				items = GestorBD.Gestor().ObtenerSolicitudes(usuarioActivo).getRegisters(); 		    				
		    			} catch (NullPointerException ex) {
							JOptionPane.showMessageDialog(mainPanel, "Problemas de conexion de usuario.  Vuelva a ingresar.");
							cardlayout.show(mainPanel, LogIn);
							return;
		         		} catch (Exception exception) {
		    				JOptionPane.showMessageDialog(mainPanel, exception.getMessage());
		    			}

		    			
		    			cantidad = items.length;
	    				mainPagePanel.getJButtonNotificaciones().setText("Notificaciones (" + cantidad + ")");			        	 	    	
						mainPagePanel.switchPanel(Notif);
		         	}
		      });
	      
	      mainPagePanel.CargarHorariosActionListener(new ActionListener() {
		         @Override
		         public void actionPerformed(ActionEvent e) {
		        	 
		        	 UsuarioActivo usuarioActivo = new UsuarioActivo(View.id, View.pass);
		        	 String[][] data = {};
		        	 try {
		        		 data = GestorBD.Gestor().ObtenerDepartamentos(usuarioActivo).getRegisters();
		        	 } catch (Exception exception) {
		        		 JOptionPane.showMessageDialog(mainPanel,exception.getMessage(), "Mensaje", JOptionPane.PLAIN_MESSAGE);	
		     			 return; 
		        	 }
		        	 
		        	 if (data.length > 0) {
							mainPagePanel.getCargarHorarios().getJComboBoxDepto().removeAllItems();
							for (int i=0; i < data.length; i++ ) {
								mainPagePanel.getCargarHorarios().getJComboBoxDepto().addItem(data[i][0] + " - " + data[i][1]);
							}
						} else {
							mainPagePanel.getCargarHorarios().getJComboBoxDepto().removeAllItems();
							mainPagePanel.getCargarHorarios().getJComboBoxDepto().addItem("(vacio)");
						}
		        	 
		        	 
		        	 mainPagePanel.switchPanel(Cargar);	    	
		        	 
		         }
		      });
	      
	      mainPagePanel.AgregarAmigosActionListener(new ActionListener() {
		         @Override
		         public void actionPerformed(ActionEvent e) {  
		        	 mainPagePanel.switchPanel(Agregar);	    	
		         }
		      });
	      
	      mainPagePanel.ConsultarActionListener(new ActionListener() {
		         @Override
		         public void actionPerformed(ActionEvent e) {  
		        	 
		        	 LoadJScrollPaneMaterias();
		        	 LoadJScrollPaneAmigos();
		        	     	
		        	 mainPagePanel.switchPanel(Consultar);
		         }
		      });
 
	      mainPagePanel.ExitActionListener(new ActionListener() {
		         @Override
		         public void actionPerformed(ActionEvent e) {
			    	cardlayout.show(mainPanel, LogIn);
			    	mainPagePanel.switchPanel(Inicio);
		         }
		      }); 
	      
	      mainPagePanel.getInicio().EliminarCuentaActionListener(new ActionListener() {
		         @Override
		         public void actionPerformed(ActionEvent e) {
		        	 
		        	 UsuarioActivo usuarioActivo = new UsuarioActivo(View.id, View.pass);
		        	 try {
		        		 GestorBD.Gestor().EliminarUsuario(usuarioActivo);
		        	 } catch (Exception exception) {
		        		 JOptionPane.showMessageDialog(mainPanel, exception.getMessage());
		        	 }
				    	cardlayout.show(mainPanel, LogIn);
				    	mainPagePanel.switchPanel(Inicio);
		         }
		      });
	   }
	   
	   private void LoadJScrollPaneMaterias() {
		   UsuarioActivo usuarioActivo = new UsuarioActivo(View.id, View.pass);
      	 	String[] fields = {"codigoMateria", "materia", "curso"};
      	 	String[][] items = {};
      	 	String[] elements = {};
      	 	Set<String> set = new HashSet<String>();
      	 
		   try {
      		 items = GestorBD.Gestor().ObtenerInscripciones(usuarioActivo).getRegisters(fields);
      		 for (int k=0; k<items.length; k++) {
	        		 set.add(items[k][0] + " - " + items[k][1] + " - " + items[k][2]);
      		 }

      		 mainPagePanel.getConsultar().getVectorMaterias().removeAllElements();
      		 elements = set.toArray(new String[0]);
      		 for (int k=0; k<set.size(); k++) {
      			 mainPagePanel.getConsultar().getVectorMaterias().addElement( elements[k] ); 
      		 }
      		 mainPagePanel.getConsultar().getJListMaterias().setListData(mainPagePanel.getConsultar().getVectorMaterias());
      		 mainPagePanel.getConsultar().getMateriasScroll().getViewport().setView(mainPagePanel.getConsultar().getJListMaterias());
      	 } catch (Exception exception) {
      		 
      	 }
	   }

	   private void LoadJScrollPaneAmigos() {
		    UsuarioActivo usuarioActivo = new UsuarioActivo(View.id, View.pass);
      	 	String[] fields = {"padron", "nombre", "apellido"};
      	 	String[][] items = {};
      	 	String[] elements = {};
      	 	Set<String> set = new HashSet<String>();
      	 
		   try {
      		 items = GestorBD.Gestor().ObtenerAmistades(usuarioActivo).getRegisters(fields);
      		 for (int k=0; k<items.length; k++) {
	        		 set.add(items[k][0] + " - " + items[k][1] + " " + items[k][2]);
      		 }
      		 
      		 elements = set.toArray(new String[0]);
      		 mainPagePanel.getConsultar().getVectorAmigos().removeAllElements();
      		 for (int k=0; k<set.size(); k++) {
      			 mainPagePanel.getConsultar().getVectorAmigos().addElement( elements[k] ); 
      		 }
      		 mainPagePanel.getConsultar().getJListAmigos().setListData(mainPagePanel.getConsultar().getVectorAmigos());
      		 mainPagePanel.getConsultar().getAmigosScroll().getViewport().setView(mainPagePanel.getConsultar().getJListAmigos());

      	 } catch (Exception exception) {
      		 
      	 }
	   }
	   private JComponent getMainComponent() {
	      return mainPanel;
	   }

	   public static void createAndShowUI() {
	      JFrame frame = new JFrame("NerdsMap App");
	      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	      frame.getContentPane().add(new View().getMainComponent());
	      frame.setSize(700,500);
	      frame.setLocationRelativeTo(null);
	      frame.setVisible(true);
	   }

}

